<template>
  <div class="login">
    <h2>登录</h2>
    <el-form ref="loginForm" :model="loginData" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginData.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();
const loginForm = ref(null);
const loginData = ref({
  username: '',
  password: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  if (!loginForm.value) return;
  try {
    await loginForm.value.validate();
    // 模拟登录验证，实际应调用后端接口
    const isAuthenticated = userStore.users.some(user => 
      user.username === loginData.value.username && user.password === loginData.value.password
    );
    if (isAuthenticated) {
      ElMessage.success('登录成功');
      // 存储登录状态
      localStorage.setItem('isLoggedIn', 'true');
      router.push('/dashboard');
    } else {
      ElMessage.error('用户名或密码错误');
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查表单信息');
  }
};
</script>

<style scoped>
.login {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>
